package com.bawei.module_goods.ui

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.lib_net.RetrofitFactory
import com.bawei.module_goods.model.SearchGoodsItem
import com.bawei.module_goods.network.GoodsApi
import com.bawei.module_goods.util.SearchHistoryManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

// UI State
data class SearchUiState(
    val loading: Boolean = false,
    val result: List<SearchGoodsItem> = emptyList(),
    val error: String? = null,
    val suggestions: List<SearchGoodsItem> = emptyList(),
    val history: List<String> = emptyList()
)

// Intent
sealed class SearchIntent {
    data class Search(val keyword: String) : SearchIntent()
    data class Suggest(val keyword: String) : SearchIntent()
    object LoadHistory : SearchIntent()
    object ClearHistory : SearchIntent()
}

class GoodsSearchViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(SearchUiState())
    val uiState: StateFlow<SearchUiState> = _uiState

    fun processIntent(context: Context, intent: SearchIntent) {
        when (intent) {
            is SearchIntent.Search -> searchGoods(context, intent.keyword)
            is SearchIntent.Suggest -> suggestGoods(intent.keyword)
            is SearchIntent.LoadHistory -> loadHistory(context)
            is SearchIntent.ClearHistory -> clearHistory(context)
        }
    }

    private fun searchGoods(context: Context, keyword: String) {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(loading = true, error = null)
            val result = searchGoodsApi(keyword)
            if (result != null) {
                _uiState.value = SearchUiState(loading = false, result = result)
            } else {
                _uiState.value = SearchUiState(loading = false, error = "搜索失败")
            }
        }
    }

    private suspend fun searchGoodsApi(keyword: String): List<SearchGoodsItem>? {
        return try {
            val api = RetrofitFactory.getRetrofitFactory().create(GoodsApi::class.java)
            val response = api.searchGoods(keyword)
            if (response.code == 200) {
                response.data ?: emptyList()
            } else null
        } catch (e: Exception) {
            null
        }
    }

    private fun suggestGoods(keyword: String) {
        viewModelScope.launch {
            val suggestions = searchGoodsApi(keyword) ?: emptyList()
            _uiState.value = _uiState.value.copy(suggestions = suggestions)
        }
    }

    private fun loadHistory(context: Context) {
        val history = SearchHistoryManager.getHistory(context)
        _uiState.value = _uiState.value.copy(history = history)
    }

    private fun clearHistory(context: Context) {
        SearchHistoryManager.clearHistory(context)
        loadHistory(context)
    }
} 